package com.zhilianbao.leyaogo.app;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.bql.convenientlog.CLog;
import com.bql.utils.CrashHandler;
import com.bql.utils.DataKeeperUtils;
import com.bql.utils.ThreadPool;
import com.facebook.stetho.Stetho;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.github.moduth.blockcanary.BlockCanary;
import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.PictureConfig;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.zhilianbao.leyaogo.BuildConfig;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.constants.CacheConfig;
import com.zhilianbao.leyaogo.constants.HttpConfig;
import com.zhilianbao.leyaogo.constants.KeyConfig;
import com.zhilianbao.leyaogo.constants.LoginConfig;
import com.zhilianbao.leyaogo.service.LeYaoGoService;
import com.zhilianbao.leyaogo.ui.activity.MainActivity;
import com.zhilianbao.leyaogo.wxapi.WXEntryActivity;
import com.zhilianbao.okhttputils.OkHttpUtils;
import com.zlb.lxlibrary.application.LeXiuApplication;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import io.rong.imkit.RongIM;

/**
 * ClassName: LeYaoGoApplication <br>
 * Description: 乐摇Go Application<br>
 * Author: Cyarie <br>
 * Created: 2016/10/17 15:20 <br>
 * Update Time：<br>
 * Update Description：<br>
 */
public class LeYaoGoApplication extends LeXiuApplication {

    private static Context mContext;

    private RefWatcher mRefWatcher;

    private static DataKeeperUtils sDataKeeperUtils;
    public static IWXAPI sApi;
    //购物车数量
    public static int SHOPPING_CART_NUM = 0;

    //是否已经获取购物车的数量
    public static boolean HAS_GOT_SHOPPING_CART_NUM = false;

    //    private ApplicationLike tinkerApplicationLike;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);//解决友盟分析问题以及分包
        // 安装tinker
        Beta.installTinker();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //我们可以从这里获得Tinker加载过程的信息
        //        if (BuildConfig.TINKER_ENABLE) {
        //            tinkerApplicationLike = TinkerPatchApplicationLike.getTinkerPatchApplicationLike();
        //            TinkerPatch.init(tinkerApplicationLike)
        //                    .reflectPatchLibrary()
        //                    .setPatchRollbackOnScreenOff(false)
        //                    .setPatchRestartOnSrceenOff(false);
        //        }
        Intent intent = new Intent(this, LeYaoGoService.class);
        startService(intent);
        mContext = getApplicationContext();
        //Log打印工具初始化
        CLog.init(BuildConfig.LOG_ENABLE);
        //内存泄漏检测
        mRefWatcher = LeakCanary.install(this);
        //数据储存工具
        sDataKeeperUtils = new DataKeeperUtils(mContext, CacheConfig.PREFERS_CONFIG);
        //Chrome调试APP 初始化
        Stetho.initialize(
                Stetho.newInitializerBuilder(this)
                        .enableDumpapp(
                                Stetho.defaultDumperPluginsProvider(this))
                        .enableWebKitInspector(
                                Stetho.defaultInspectorModulesProvider(this))
                        .build());
        OkHttpUtils.init(this);
        try {
            OkHttpUtils.getInstance()
                    .debug(BuildConfig.LOG_ENABLE) //是否打开调试 打印信息
                    .addNetworkInterceptor(new StethoInterceptor()) //集成Stetho
                    .setConnectTimeout(HttpConfig.CONN_TIME_OUT) //全局的连接超时时间
                    .setReadTimeOut(HttpConfig.WRITE_TIME_OUT)//全局的读取超时时间
                    .setWriteTimeOut(HttpConfig.READ_TIME_OUT)  //全局的写入超时时间
                    .setCertificates(getAssets().open("leyao.cer"))
                    .setHostnameVerifier((hostname, session) ->
                            hostname.equals(BuildConfig.HOST_NAME)
                    )
                    .setRetryCount(0);//全局超时重连次数
        } catch (IOException e) {
            e.printStackTrace();
        }
        //设置默认的异常捕获处理器
        Thread.setDefaultUncaughtExceptionHandler(CrashHandler.getInstance(this, CacheConfig.CRASH_CACHE_NAME));
        //皮肤初始化
        //        SkinManager.getInstance().init(this);
        //线程池初始化
        ThreadPool.startup();
        //初始化图片选择器
        //        initialPickPhotos();
        //性能监控
        BlockCanary.install(this, new GoBlockCanaryContext()).start();
        /**
         * 初始化融云
         */
        RongIM.init(this);

        // 初始化微信组件
        initWeiXin();

        /**
         * 初始化Bugly
         */
        initTecentBugly();

        //初始化路由
        //        ARouter.init(this);

    }

    private void initWeiXin() {
        sApi = WXEntryActivity.initWeiXin(this, LoginConfig.WEIXIN_APP_ID);
    }

    /**
     * 初始化配置PickPhotos
     */
    private void initialPickPhotos() {
        //        int color = getResources().getColor(R.color.toolbar_background_color);
        //        //设置主题
        //        ThemeConfig theme = new ThemeConfig.Builder()
        //                .setTitleBarBgColor(color)
        //                .setCheckSelectedColor(color)
        //                .build();
        //        //配置功能
        //        FunctionConfig functionConfig = new FunctionConfig.Builder()
        //                .setEnableCrop(false)//可裁剪
        //                .setEnableRotate(false)//可旋转
        //                .setEnablePreview(true)//可预览
        //                .setEnableEdit(true)//可编辑
        //                .build();
        //        //设置核心功能
        //        CoreConfig coreConfig = new CoreConfig.Builder(this, new GlideImageLoader(), theme)
        //                .setDebug(BuildConfig.LOG_ENABLE)
        //                .setFunctionConfig(functionConfig)
        //                .setPauseOnScrollListener(new GlidePauseOnScrollListener(false, true))
        //                .build();
        //        //图片选择初始化
        //        PickPhotos.init(coreConfig);
        FunctionConfig functionConfig = new FunctionConfig();
        functionConfig.setImageFolder(CacheConfig.IMAGE_COMPRESS_FOLDER);
        functionConfig.setImagePrefix(CacheConfig.IMAGE_PREFIX);
        PictureConfig.init(functionConfig);
    }


    public static Context getContext() {
        return mContext;
    }

    /**
     * 内存泄漏检测
     *
     * @param context
     * @return
     */
    public static RefWatcher getRefWatcher(Context context) {
        LeYaoGoApplication application = (LeYaoGoApplication) context.getApplicationContext();
        return application.mRefWatcher;
    }

    public static DataKeeperUtils getDataKeeper() {
        return sDataKeeperUtils;
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        android.os.Process.killProcess(android.os.Process.myPid());
    }


    /**
     * 初始化Tecent Bugly
     */
    private void initTecentBugly() {
        // 获取当前包名
        String packageName = this.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(this);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        /***** Beta高级设置 *****/
        /**
         * true表示app启动自动初始化升级模块;
         * false不会自动初始化;
         * 开发者如果担心sdk初始化影响app启动速度，可以设置为false，
         * 在后面某个时刻手动调用Beta.init(getApplicationContext(),false);
         */
        Beta.autoInit = true;

        /**
         * true表示初始化时自动检查升级;
         * false表示不会自动检查升级,需要手动调用Beta.checkUpgrade()方法;
         */
        Beta.autoCheckUpgrade = true;

        /**
         * 设置升级检查周期为60s(默认检查周期为0s)，60s内SDK不重复向后台请求策略);
         */
        //            Beta.upgradeCheckPeriod = 60 * 1000;

        /**
         * 设置启动延时为1s（默认延时3s），APP启动1s后初始化SDK，避免影响APP启动速度;
         */
        //            Beta.initDelay = 1 * 1000;

        //        /**
        //         * 设置通知栏大图标，largeIconId为项目中的图片资源;
        //         */
        //        Beta.largeIconId = R.drawable.ic_launcher;
        //
        //        /**
        //         * 设置状态栏小图标，smallIconId为项目中的图片资源Id;
        //         */
        //        Beta.smallIconId = R.drawable.ic_launcher;

        //        /**
        //         * 设置更新弹窗默认展示的banner，defaultBannerId为项目中的图片资源Id;
        //         * 当后台配置的banner拉取失败时显示此banner，默认不设置则展示“loading“;
        //         */
        //        Beta.defaultBannerId = R.drawable.ic_launcher;

        /**
         * 设置sd卡的Download为更新资源保存目录;
         * 后续更新资源会保存在此目录，需要在manifest中添加WRITE_EXTERNAL_STORAGE权限;
         */
        Beta.storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

        /**
         * 点击过确认的弹窗在APP下次启动自动检查更新时会再次显示;
         */
        Beta.showInterruptedStrategy = true;

        /**
         * 只允许在MainActivity上显示更新弹窗，其他activity上不显示弹窗;
         * 不设置会默认所有activity都可以显示弹窗;
         */
        Beta.canShowUpgradeActs.add(MainActivity.class);

        /**
         *  设置自定义升级对话框UI布局
         *  注意：因为要保持接口统一，需要用户在指定控件按照以下方式设置tag，否则会影响您的正常使用：
         *  标题：beta_title，如：android:tag="beta_title"
         *  升级信息：beta_upgrade_info  如： android:tag="beta_upgrade_info"
         *  更新属性：beta_upgrade_feature 如： android:tag="beta_upgrade_feature"
         *  取消按钮：beta_cancel_button 如：android:tag="beta_cancel_button"
         *  确定按钮：beta_confirm_button 如：android:tag="beta_confirm_button"
         *  详见layout/upgrade_dialog.xml
         */
        Beta.upgradeDialogLayoutId = R.layout.dialog_upgrade_bugly;

        //            Beta.upgradeListener = (i, upgradeInfo, b, b1) -> {
        //                CLog.e(upgradeInfo.toString());
        //                if (upgradeInfo != null) {
        //                    CLog.json(upgradeInfo.toString());
        //                }
        //            };

        // 初始化Bugly 带有版本检测更新、热更新功能
        Bugly.init(this, KeyConfig.TECENT_BUGLY_APP_ID, BuildConfig.LOG_ENABLE, strategy);
        //        } else {
        //            // 初始化Bugly 只有错误上报功能
        //            CrashReport.initCrashReport(this, KeyConfig.TECENT_BUGLY_APP_ID, BuildConfig.LOG_ENABLE, strategy);
        //        }

    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    public static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

}
